package com.easa.controller;

import com.alibaba.fastjson.JSONObject;
import com.easa.bean.CurrentWeek;
import com.easa.dao.TeacherMsgDao;
import com.easa.entity.*;
import com.easa.service.LaboratorymsgService;
import com.easa.service.TeacherMsgService;
import com.easa.service.TimetableService;
import com.easa.service.WeektableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/timetable")
public class TimetableController {

    @Autowired
    private TimetableService timetableService;

    @Autowired
    private LaboratorymsgService laboratorymsgService;

    @Autowired
    private WeektableService weektableService;

    @Autowired
    private TeacherMsgService teacherMsgService;

    /*获取课程号页面数据*/
    @RequestMapping(value="",method= RequestMethod.GET)
    @ResponseBody
    public Object get(HttpServletRequest request) throws ParseException {

        Date today = new Date();
        Weektable nowWeek = weektableService.findWeekidByNow(today);
        String tid = "1400310502";
        ShowTeacherMsg showTeacherMsg = teacherMsgService.findTeacherMsgByid(tid);
        nowWeek.setSemester(weektableService.findSemesterName(nowWeek.getSemester()));
        List<ShowTimetableByDay> showTimetableByDays = timetableService.findCourseWithToday(today,nowWeek.getWeekid());
        List<Laboratorymsg> laboratorymsg = laboratorymsgService.findAllLaboratorymsg();
        for (ShowTimetableByDay showTimetableByDay : showTimetableByDays ){
            for(int i = 0; i < laboratorymsg.size(); i++){
                if(showTimetableByDay.getLid() == laboratorymsg.get(i).getLid()){
                    showTimetableByDay.setXNum(i+1);
                        break;
                }
            }

        }

        JSONObject js = new JSONObject();
        js.put("timetable", showTimetableByDays);
        js.put("teacherMsg",showTeacherMsg);
        js.put("fromX",laboratorymsg);
        js.put("thisweek",nowWeek);
        return js;
    }

    /*获取课程查看设置页面数据*/
    @RequestMapping(value="findConditionsByGET",method= RequestMethod.GET)
    @ResponseBody
    public Object findConditions(HttpServletRequest request) throws ParseException {

        String name = request.getParameter("username");
        ShowTeacherMsg teachermsg = teacherMsgService.findTeacherMsgByid(name);
        List<Semester> semester = weektableService.findSemester();
        //查找并返回当前周的id
        CurrentWeek currentWeek = weektableService.findCurrentWeek();
        JSONObject js = new JSONObject();
        js.put("teachermsg", teachermsg);
        js.put("semester", semester);
        js.put("currentWeek",currentWeek);
        return js;
    }

    /*获取课程查看设置页面数据*/
    @RequestMapping(value="findConditions",method= RequestMethod.POST)
    @ResponseBody
    public Object findConditionsByPost(HttpServletRequest request) throws ParseException {

        String name = request.getParameter("username");
        ShowTeacherMsg teachermsg = teacherMsgService.findTeacherMsgByid(name);
        List<Semester> semester = weektableService.findSemester();
        //查找并返回当前周的id
        CurrentWeek currentWeek = weektableService.findCurrentWeek();
        JSONObject js = new JSONObject();
        js.put("teachermsg", teachermsg);
        js.put("semester", semester);
        js.put("currentWeek",currentWeek);
        return js;
    }


    /*存入选择查看状态*/
    /*@RequestMapping(value="setConditions",method= RequestMethod.POST)
    @ResponseBody
    public Object setConditions(HttpServletRequest request) throws ParseException {

        String name = request.getParameter("username");
        String viewClassify = request.getParameter("viewClassify");
        String checkWay = request.getParameter("checkWay");
        String semesterName = request.getParameter("semesterName");
        String weeknum = request.getParameter("weekid");
        String semesterId = weektableService.findSemesterId(semesterName);
        String weekid = semesterId+"_"+weeknum;
        teacherMsgService.setConditionsByTid(name,viewClassify,checkWay,semesterId,weekid);

        JSONObject js = new JSONObject();
        js.put("isSuccess", "success");
        return js;
    }*/

    /*预选课*/
    @RequestMapping(value="setClass",method= RequestMethod.POST)
    @ResponseBody
    public Object setClassPost(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        JSONObject js = new JSONObject();
        String lessonName = request.getParameter("lessonName");
        String tidStr = request.getParameter("tid");
        String classNumStr = request.getParameter("classNum");
        String classLengthStr = request.getParameter("classLength");
        String weekid = request.getParameter("weekid");
        String classDate = request.getParameter("classDate");
        String classClassify = request.getParameter("classClassify");
        String applicationName = request.getParameter("applicationName");
        String lidStr = request.getParameter("lid");
        String weekdayStr = request.getParameter("weekday");
        String batchNumStr = request.getParameter("batchNum");

        //验证该教职工号在后台是否存在
        Teachermsg teachermsg = teacherMsgService.findTeacherDetailByAdmin(tidStr);
        if(teachermsg==null){
            js.put("isSuccess", 3); //表示该教工号不存在
            return js;
        }


        int classNum = 0;
        int classLength = 0;
        int lid = 0;
        int classClassifyNum = 0 ;
        int weekday = 0;
        int batchNum = 0;

        //空值则插入失败
        if (classNumStr!=null && !classNumStr.equals("")){
            try {
                classNum = Integer.valueOf(classNumStr);
            }catch (Exception e) {
                js.put("isSuccess", 1);
                return js;
            }
        }else {
            js.put("isSuccess", 1);
            return js;
        }

        if(classLengthStr!=null && !classLengthStr.equals("")){
            try {
                classLength = Integer.valueOf(classLengthStr);
            }catch (Exception e){
                js.put("isSuccess", 1);
                return js;
            }
        }else {
            js.put("isSuccess", 1);
            return js;
        }

        if(lidStr!=null && !lidStr.equals("")){
            try {
                lid = Integer.valueOf(lidStr);
            }catch (Exception e){
                js.put("isSuccess", 1);
                return js;
            }
        }else {
            js.put("isSuccess", 1);
            return js;
        }

        if (classClassify!=null && !classClassify.equals("")){
            try {
                classClassifyNum = Integer.valueOf(classClassify);
            }catch (Exception e){
                js.put("isSuccess", 1);
                return js;
            }
        }else {
            js.put("isSuccess", 1);
            return js;
        }

        if (weekdayStr!=null && !weekdayStr.equals("")){
            try {
                weekday = Integer.valueOf(weekdayStr);
            }catch (Exception e){
                js.put("isSuccess", 1);
                return js;
            }
        }else {
            js.put("isSuccess", 1);
            return js;
        }

        if (batchNumStr!=null && !batchNumStr.equals("")){
            try {
                batchNum = Integer.valueOf(batchNumStr);
            }catch (Exception e){
                js.put("isSuccess", 1);
                return js;
            }
        }else {
            js.put("isSuccess", 1);
            return js;
        }

        Timetable timetable = new Timetable();
        timetable.setLessonName(lessonName);
        timetable.setTid(tidStr);
        timetable.setClassNum(classNum);
        timetable.setClassLength(classLength);
        timetable.setWeekid(weekid);
        timetable.setClassDate(classDate);
        timetable.setApplicationName(applicationName);
        timetable.setClassClassify(classClassifyNum);
        timetable.setLid(lid);
        timetable.setWeekday(weekday);
        timetable.setBatchNum(batchNum);

        //返回0成功，1出错，2冲突
        int isSuccess = timetableService.insertClass(timetable);
        js.put("isSuccess", isSuccess);
        js.put("timeTable",timetable);
        return js;
    }

    /*获取课程号页面数据*/
    @RequestMapping(value="updateData",method= RequestMethod.POST)
    @ResponseBody
    public Object updateDate(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        String tid = request.getParameter("userId");
        String searchDate = request.getParameter("searchDate");
        String tableSign = request.getParameter("tableSign");
        List<ShowTimetableByDay> showTimetableByDays;
        Weektable nowWeek = weektableService.findWeekidBydateStr(searchDate);
        if (tableSign.equals("all"))
            showTimetableByDays = timetableService.findAllCourse(searchDate,nowWeek.getWeekid());
        else
            showTimetableByDays = timetableService.findPersonCourse(searchDate,tid);
        List<Laboratorymsg> laboratorymsg = laboratorymsgService.findAllLaboratorymsg();
        for (ShowTimetableByDay showTimetableByDay : showTimetableByDays ){
            for(int i = 0; i < laboratorymsg.size(); i++){
                if(showTimetableByDay.getLid() == laboratorymsg.get(i).getLid()){
                    showTimetableByDay.setXNum(i+1);
                    break;
                }
            }
        }

        JSONObject js = new JSONObject();
        js.put("timetable", showTimetableByDays);
        return js;
    }

    /*获取课程学期*/
    @RequestMapping(value="findSemesters",method= RequestMethod.GET)
    @ResponseBody
    public Object findSemesters(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        List<Semester> semesters = weektableService.findSemester();

        JSONObject js = new JSONObject();
        js.put("semesters", semesters);
        return js;
    }

    /*更新课表周次和选择*/
    @RequestMapping(value="updateTitleAndDate",method= RequestMethod.POST)
    @ResponseBody
    public Object updateTitle(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        String weekid = request.getParameter("weekid");

        Weektable weektable = weektableService.findWeekById(weekid);
        weektable.setSemester(weektableService.findSemesterName(weektable.getSemester()));
        JSONObject js = new JSONObject();
        js.put("weekMsg", weektable);
        return js;
    }

    /*获取课程号页面数据*/
    @RequestMapping(value="getPersonClass",method= RequestMethod.POST)
    @ResponseBody
    public Object getPersonClass(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        String tid = request.getParameter("tid");
        Date today = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String  todayStr = sf.format(today);

        Weektable thisWeek = weektableService.findWeekidByNow(today);
        List<ShowTimetableByDay> timetables = timetableService.findPersonCourse(todayStr,tid);

        JSONObject js = new JSONObject();
        js.put("timetables",timetables );
        return js;
    }

    /*获取课程号页面数据GET*/
    @RequestMapping(value="getPersonClassByGET",method= RequestMethod.GET)
    @ResponseBody
    public Object getPersonClassByGET(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        String tid = request.getParameter("tid");
        Date today = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String  todayStr = sf.format(today);

        Weektable thisWeek = weektableService.findWeekidByNow(today);
        List<ShowTimetableByDay> timetables = timetableService.findPersonCourse(todayStr,tid);

        JSONObject js = new JSONObject();
        js.put("timetables",timetables );
        return js;
    }

    /*获取我的课程号页面数据POST*/
    @RequestMapping(value="getPersonClassAWeek",method= RequestMethod.POST)
    @ResponseBody
    public Object getPersonClassAWeek(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        String tid = request.getParameter("tid");
        Date today = new Date();

        Weektable thisWeek = weektableService.findWeekidByNow(today);
        thisWeek.setSemester(weektableService.findSemesterName(thisWeek.getSemester()));
        List<ShowTimetableByDay> timetables = timetableService.findPersonCourseAWeek(thisWeek.getWeekid(),tid);

        JSONObject js = new JSONObject();
        js.put("thisWeek",thisWeek);
        js.put("timetables",timetables );
        return js;
    }


    /*获取我的课程号页面数据Get*/
    @RequestMapping(value="getPersonClassAWeekByGet",method= RequestMethod.GET)
    @ResponseBody
    public Object getPersonClassAWeekGet(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        String tid = request.getParameter("tid");
        Date today = new Date();

        Weektable thisWeek = weektableService.findWeekidByNow(today);
        thisWeek.setSemester(weektableService.findSemesterName(thisWeek.getSemester()));
        List<ShowTimetableByDay> timetables = timetableService.findPersonCourseAWeek(thisWeek.getWeekid(),tid);

        JSONObject js = new JSONObject();
        js.put("thisWeek",thisWeek);
        js.put("timetables",timetables);
        return js;
    }


    /*获取我的课程详细页面数据POST*/
    @RequestMapping(value="getClassDetail",method= RequestMethod.POST)
    @ResponseBody
    public Object getClassDetail(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        String cidStr = request.getParameter("cid");
        int cid = 0;
        try {
            cid = Integer.parseInt(cidStr);
        }catch (Exception e){
            System.out.println(e);
        }

        ShowTimetableByDay timetable = timetableService.findTimetableByCid(cid);

        JSONObject js = new JSONObject();
        js.put("timetable",timetable);
        return js;
    }

    /*删除我的课程详细页面数据POST*/
    @RequestMapping(value="deleteClass",method= RequestMethod.POST)
    @ResponseBody
    public Object deleteClass(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        String cidStr = request.getParameter("cid");
        int cid = 0;
        try {
            cid = Integer.parseInt(cidStr);
        }catch (Exception e){
            System.out.println(e);
        }

        int isSuccess = timetableService.deleteClassByCid(cid);

        JSONObject js = new JSONObject();
        js.put("isSuccess",isSuccess);
        return js;
    }

    /*更新我的课程号页面数据POST*/
    @RequestMapping(value="updateMyClass",method= RequestMethod.POST)
    @ResponseBody
    public Object updateMyClass(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        String tid = request.getParameter("tid");
        String weekid = request.getParameter("weekid");

        Weektable thisWeek = weektableService.findWeekById(weekid);
        thisWeek.setSemester(weektableService.findSemesterName(thisWeek.getSemester()));
        List<ShowTimetableByDay> timetables = timetableService.findPersonCourseAWeek(thisWeek.getWeekid(),tid);

        JSONObject js = new JSONObject();
        js.put("thisWeek",thisWeek);
        js.put("timetables",timetables);
        return js;
    }

    //获取实验课程信息
    @RequestMapping(value="findClassByAdmin",method= RequestMethod.POST)
    @ResponseBody
    public Object findClassByAdmin(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        String tid = request.getParameter("tid");
        String lname = request.getParameter("lname");
        String classdate = request.getParameter("classdate");

        List<ShowTimetableByDay> timetables = timetableService.getClassByAdmin(tid,lname,classdate);

        JSONObject js = new JSONObject();
        js.put("classes",timetables);
        return js;
    }

    //获取实验课程详细信息（后台管理）
    @RequestMapping(value="findClassByCid",method= RequestMethod.POST)
    @ResponseBody
    public Object findClassByCid(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        String cidStr = request.getParameter("cid");

        int cid = 0;
        ShowTimetableByDay timetable = null;
        try {
            cid = Integer.parseInt(cidStr);
            timetable = timetableService.findTimetableByCid(cid);
        }catch (Exception e){
            System.out.println("cid转换int异常:"+e+"cid:"+cid);
        }

        JSONObject js = new JSONObject();
        js.put("class",timetable);
        return js;
    }
}
